import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useNewsStore = defineStore('news', () => {
  // 状态定义
  const newsCache = ref(new Map())
  const categories = ref([])
  const sections = ref([])
  const latestNews = ref([])
  const searchResults = ref([])
  const loading = ref(false)
  
  // 分页状态
  const currentPage = ref(1)
  const totalPages = ref(0)
  const pageSize = ref(10)
  
  // 搜索状态
  const searchKeyword = ref('')
  const selectedCategory = ref('')
  const selectedSection = ref('')

  // 计算属性
  const hasCache = computed(() => newsCache.value.size > 0)
  const hasCategories = computed(() => categories.value.length > 0)
  const hasSections = computed(() => sections.value.length > 0)
  const hasSearchResults = computed(() => searchResults.value.length > 0)
  
  const getCachedNews = computed(() => (newsId) => {
    return newsCache.value.get(newsId)
  })

  const isLastPage = computed(() => currentPage.value >= totalPages.value)
  const isFirstPage = computed(() => currentPage.value <= 1)

  // Actions
  const cacheNews = (newsId, newsData) => {
    // 缓存新闻数据，设置过期时间（30分钟）
    const cacheData = {
      data: newsData,
      timestamp: Date.now(),
      expiry: Date.now() + 30 * 60 * 1000 // 30分钟过期
    }
    newsCache.value.set(newsId, cacheData)
    
    // 限制缓存大小，最多缓存100条新闻
    if (newsCache.value.size > 100) {
      const firstKey = newsCache.value.keys().next().value
      newsCache.value.delete(firstKey)
    }
  }

  const getCachedNewsData = (newsId) => {
    const cached = newsCache.value.get(newsId)
    if (cached) {
      // 检查是否过期
      if (Date.now() < cached.expiry) {
        return cached.data
      } else {
        // 过期则删除
        newsCache.value.delete(newsId)
      }
    }
    return null
  }

  const clearExpiredCache = () => {
    const now = Date.now()
    for (const [key, value] of newsCache.value.entries()) {
      if (now >= value.expiry) {
        newsCache.value.delete(key)
      }
    }
  }

  const loadCategories = async (api) => {
    try {
      const result = await api.getCategories()
      if (result && Array.isArray(result)) {
        categories.value = result
      } else if (result.code === 200 && Array.isArray(result.data)) {
        categories.value = result.data
      }
      return { success: true, data: categories.value }
    } catch (error) {
      console.error('加载分类失败:', error)
      return { success: false, error: error.message }
    }
  }

  const loadSections = async (api) => {
    try {
      const result = await api.getSections()
      if (result && Array.isArray(result)) {
        sections.value = result
      } else if (result.code === 200 && Array.isArray(result.data)) {
        sections.value = result.data
      }
      return { success: true, data: sections.value }
    } catch (error) {
      console.error('加载学院列表失败:', error)
      return { success: false, error: error.message }
    }
  }

  const loadLatestNews = async (api, page = 1, size = 10) => {
    try {
      loading.value = true
      const result = await api.getLatestArticles({ page, size })
      
      if (result && result.code === 200) {
        const { articles, pageNum, pages, total } = result.data
        
        if (page === 1) {
          latestNews.value = articles
        } else {
          latestNews.value.push(...articles)
        }
        
        currentPage.value = pageNum
        totalPages.value = pages
        
        // 缓存新闻数据
        articles.forEach(article => {
          const newsId = article.news_id || article.newsId
          if (newsId) {
            cacheNews(newsId, article)
          }
        })
        
        return { success: true, data: result.data }
      }
      
      return { success: false, message: '获取新闻失败' }
    } catch (error) {
      console.error('加载最新新闻失败:', error)
      return { success: false, error: error.message }
    } finally {
      loading.value = false
    }
  }

  const searchNews = async (api, params) => {
    try {
      loading.value = true
      const result = await api.searchArticles(params)
      
      if (result && result.code === 200) {
        const { articles, pageNum, pages } = result.data
        
        if (params.page === 1) {
          searchResults.value = articles
        } else {
          searchResults.value.push(...articles)
        }
        
        currentPage.value = pageNum
        totalPages.value = pages
        
        // 更新搜索条件
        searchKeyword.value = params.keyword || ''
        selectedCategory.value = params.category || ''
        selectedSection.value = params.section || ''
        
        // 缓存搜索结果
        articles.forEach(article => {
          const newsId = article.news_id || article.newsId
          if (newsId) {
            cacheNews(newsId, article)
          }
        })
        
        return { success: true, data: result.data }
      }
      
      return { success: false, message: '搜索失败' }
    } catch (error) {
      console.error('搜索新闻失败:', error)
      return { success: false, error: error.message }
    } finally {
      loading.value = false
    }
  }

  const getNewsDetail = async (api, newsId) => {
    try {
      // 先检查缓存
      const cached = getCachedNewsData(newsId)
      if (cached) {
        return { success: true, data: cached, fromCache: true }
      }
      
      // 从API获取
      const result = await api.getArticleDetail(newsId)
      let newsData
      
      if (result && result.code === 200) {
        newsData = result.data
      } else {
        newsData = result
      }
      
      if (newsData) {
        // 缓存数据
        cacheNews(newsId, newsData)
        return { success: true, data: newsData, fromCache: false }
      }
      
      return { success: false, message: '获取新闻详情失败' }
    } catch (error) {
      console.error('获取新闻详情失败:', error)
      return { success: false, error: error.message }
    }
  }

  const clearSearchResults = () => {
    searchResults.value = []
    searchKeyword.value = ''
    selectedCategory.value = ''
    selectedSection.value = ''
    currentPage.value = 1
    totalPages.value = 0
  }

  const clearAllCache = () => {
    newsCache.value.clear()
  }

  const resetPagination = () => {
    currentPage.value = 1
    totalPages.value = 0
  }

  // 定期清理过期缓存
  setInterval(clearExpiredCache, 5 * 60 * 1000) // 每5分钟清理一次

  return {
    // 状态
    newsCache,
    categories,
    sections,
    latestNews,
    searchResults,
    loading,
    currentPage,
    totalPages,
    pageSize,
    searchKeyword,
    selectedCategory,
    selectedSection,
    
    // 计算属性
    hasCache,
    hasCategories,
    hasSections,
    hasSearchResults,
    getCachedNews,
    isLastPage,
    isFirstPage,
    
    // Actions
    cacheNews,
    getCachedNewsData,
    clearExpiredCache,
    loadCategories,
    loadSections,
    loadLatestNews,
    searchNews,
    getNewsDetail,
    clearSearchResults,
    clearAllCache,
    resetPagination
  }
})
